<template>
  <view class="upload-box">
    <view class="grid col-3 grid-square flex-sub">
      <view
        class="bg-img"
        v-for="(item, index) in imageList"
        :key="index"
        @tap="ViewImagefm"
        :data-url="imageList[index].url"
      >
        <image
          v-if="addImgUrl"
          :src="imageList[index].url"
          mode="aspectFit"
          style="border-radius: 50%; top: 0; left: 0"
        />
        <image v-else :src="imageList[index].url" mode="aspectFit" />
        <view class="maskimg" v-show="item.isShow"></view>
        <cCircle
          class="cCircle"
          v-show="item.isShow"
          :class="item.progress == 100 ? 'hide1' : ''"
          :circleWidth="4"
          :size="60"
          :percent="Number(item.progress)"
        ></cCircle>
        <view class="close" @tap.stop="DelImgfm" :data-index="index" v-if="!disabled">
          <text class="cuIcon-close"></text>
        </view>
      </view>

      <view class="solids" @tap="ChooseImages()" v-if="imageList.length < lengthNum">
        <img v-if="addImgUrl" :src="addImgUrl" style="width: 100%; height: 100%" alt="" />
        <text v-else class="cuIcon-cameraadd"></text>
      </view>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <cropper ref="croop" v-show="showCroop" :sourceType='sourceType' :quality="1" resize: false
    :canScale="true" :selWidth="selWidth" :selHeight="selHeight" style='z-index:1001'
    @upload="myUpload" @changeFile="showCroop = true" @upClose="showCroop = false"
    class="userHeader" />
    <!-- #endif -->
    <!-- #ifndef MP-WEIXIN-->
    <gmy-img-cropper
      ref="gmyImgCropper"
      :sourceType="sourceType"
      quality="1"
      cropperType="ratio"
      :ratio="ratio"
      fileType="png"
      imgSrc=""
      style="z-index: 1001"
      @getImg="myUpload"
    >
    </gmy-img-cropper>
    <!-- #endif -->
  </view>
</template>

<script>
  import cCircle from './circle.vue'
  //#ifdef MP-WEIXIN
  import cropper from './lxiaoxiao-cropper/lxiaoxiao-cropper.vue'
  //#endif

  // #ifndef MP-WEIXIN
  import gmyImgCropper from './gmy-img-cropper/gmy-img-cropper.vue'
  //#endif
  export default {
    props: {
      lengthNum: {
        type: Number,
        default: 1,
      },
      value: {
        type: Array,
        default: [],
      },
      selWidth: {
        type: String,
        default: '600rpx',
      },
      selHeight: {
        type: String,
        default: '400rpx',
      },
      ratio: {
        type: Number,
        default: 1.5,
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      sourceType: {
        type: Array,
        default: () => {
          return ['camera', 'album']
        },
      },
      addImgUrl: {
        type: String,
        default: '',
      },
      deleteImg: {
        type: Function,
        default: () => {},
      },
    },
    components: {
      cCircle,
      // #ifndef MP-WEIXIN
      gmyImgCropper,
      //#endif
      //#ifdef MP-WEIXIN
      cropper,
      //#endif
    },
    data() {
      return {
        imageList: [],
        imgList: [],
        // 小程序裁剪是否展示
        showCroop: false,
      }
    },
    methods: {
      // 标题图片裁剪
      ViewImagefm(e) {
        uni.previewImage({
          urls: this.imgList,
          current: e.currentTarget.dataset.url,
        })
      },
      DelImgfm(e) {
        uni.showModal({
          title: '',
          content: '确定要删除图片？',
          cancelText: '取消',
          confirmText: '确定',
          success: (res) => {
            if (res.confirm) {
              this.imageList.splice(e.currentTarget.dataset.index, 1)
              this.$emit('deleteImg', e.currentTarget.dataset.index)
            }
          },
        })
      },
      async ChooseImages(menthType, type) {
        this.otherChooseImage()
      },
      otherChooseImage() {
        // #ifdef MP-WEIXIN
        // this.showCroop = true;
        this.$refs.croop.fSelect()
        //  #endif
        // #ifndef MP-WEIXIN
        this.$refs.gmyImgCropper.chooseImage()
        //  #endif
      },
      myUpload(rsp) {
        let filePath = ''
        // #ifndef MP-WEIXIN
        filePath = rsp
        // #endif
        // #ifdef MP-WEIXIN
        filePath = rsp.path
        // this.showCroop = false;
        //  #endif
        var _this = this
        this.imageList = []
        var uper
        uni.showToast({
          title: '正在上传请稍后',
          icon: 'none',
          duration: 2000,
        })

        _this.imageList.push({
          url: filePath,
          progress: 0,
          isShow: true,
        })
        uper = uni.uploadFile({
          // 需要上传的地址
          url: 'https://www.bangbangtongcheng.com/conven/ht/attach/qnUpload',
          // filePath 需要上传的文件
          filePath: filePath,
          name: 'file',
          success(res1) {
            _this.imageList[0].url = JSON.parse(res1.data).data[0].url
            setTimeout(() => {
              _this.imageList[0].isShow = false
            }, 1000)
          },
        })
        uper.onProgressUpdate(function (res) {
          // console.log(res);
          _this.imageList[0].progress = res.progress
        })
      },
      ChooseImage() {
        let _this = this
        let num = 0
        num = _this.lengthNum - _this.imageList.length
        uni.chooseImage({
          count: num,
          sizeType: ['copressed'],
          sourceType: this.sourceType,
          success(res) {
            //因为有一张图片， 输出下标[0]， 直接输出地址
            // console.log(res.tempFilePaths);
            var imgFiles = res.tempFilePaths
            const tempFiles = res.tempFiles
            let resSize = tempFiles[0].size
            console.log('上传数据的大小是：' + resSize)
            if (resSize > 20971520) {
              uni.showToast({
                title: '上传图片大小不能超过20MB',
                icon: 'error',
              })
              return
            }
            if (_this.imageList.length + imgFiles.length > _this.lengthNum) {
              uni.showToast({
                title: `图片最多不能超过${_this.lengthNum}张`,
                duration: 2000,
                icon: 'none',
              })
              return
            }
            let length1 = _this.imageList.length
            var uper
            imgFiles.forEach((el, index) => {
              let index1 = length1 + index
              _this.imageList.push({
                url: el,
                progress: 0,
                isShow: true,
              })
              uni.showToast({
                title: '正在上传请稍后',
                icon: 'none',
                duration: 2000,
              })
              uper = uni.uploadFile({
                // 需要上传的地址
                url: 'https://www.bangbangtongcheng.com/conven/ht/attach/qnUpload',
                // filePath  需要上传的文件
                filePath: el,
                name: 'file',
                success(res1) {
                  _this.imageList[index1].url = JSON.parse(res1.data).data[0].url
                  setTimeout(() => {
                    _this.$emit('returnSuccess')
                  }, 500)
                  setTimeout(() => {
                    _this.imageList[index1].isShow = false
                  }, 2000)
                },
              })
              // onProgressUpdate 上传对象更新的方法
              uper.onProgressUpdate(function (res) {
                // console.log(res);
                _this.imageList[index1].progress = res.progress
              })
            })
          },
          fail: (fail) => {
            if (this.$userActiveCancalAct.some(v => fail.errMsg.includes(v.failMsg))) {
              return false;
            }
            this.$SHOWMODAL_TO_SETTINGS();
          },
        })
      },
    },
    watch: {
      imageList: {
        deep: true,
        handler(newVal, oldVal) {
          let isTrue = false
          let arr = this.imageList.map((el) => {
            if (el.isShow == true || el.progress !== 100) {
              isTrue = true
            }
            return el.url
          })
          this.imgList = arr
          if (isTrue) return
          this.$emit('input', arr)
          this.$emit('returnSuccess')
        },
      },
      value: {
        deep: true,
        immediate: true,
        handler(newVal, oldVal) {
          if (this.imgList == this.value) {
            if (this.imageList.length != this.imgList.length) {
              let arr = this.value.map((el) => {
                return {
                  url: el,
                  progress: 0,
                  isShow: false,
                }
              })
              this.imageList = arr
            }
            return
          }
          let arr = this.value.map((el) => {
            return {
              url: el,
              progress: 0,
              isShow: false,
            }
          })
          this.imgList = JSON.parse(JSON.stringify(this.value))
          this.imageList = arr
        },
      },
    },
  }
</script>

<style lang="scss" scoped>
  .upload-box {
    width: 100%;
    height: 100%;
  }

  .grid.col-3.grid-square {
    display: flex;

    .bg-img {
      width: 212rpx;
      height: 212rpx;

      img {
        box-shadow: 0px 0px 6px 1px rgba(67, 67, 67, 0.16);
      }
    }

    /* #ifdef MP */
    .solids {
      width: 212rpx;
      height: 212rpx;
    }

    /* #endif */
    .solids {
      padding: 0;
      width: 212rpx;
      height: 212rpx;
    }
  }

  .grid.grid-square {
    overflow: visible;
  }

  .grid.col-3.grid-square > .bg-img:nth-child(3n),
  .grid.col-3.grid-square > .solids:nth-child(3n) {
    margin-right: 0;
  }

  .bg-img {
    position: relative;

    .close {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      right: 0;
      top: 0;
      background: rgba(0, 0, 0, 0.5);
      color: #fff;
    }

    .cCircle {
      // background: rgba(0,0,0,0.5);
      width: 120rpx;
      height: 120rpx;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .maskimg {
      background: rgba(0, 0, 0, 0.5);
      width: 100%;
      height: 100%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .hide1 {
      animation: change 3s;
    }

    @keyframes change {
      0% {
        opacity: 1;
      }

      100% {
        opacity: 0;
      }
    }
  }
</style>
